package com.jacksen.demo.view.aidl;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.jacksen.demo.view.R;

public class TestAidlActivity extends AppCompatActivity {

    private static final int MSG_DOWNLOAD_PROGRESS = 0x1;
    private IDownloadService downloadService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_aidl);

        // 绑定远程服务
        Intent intent = new Intent(this, DownloadService.class);
        bindService(intent, mConnection, BIND_AUTO_CREATE);
    }


    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadService = IDownloadService.Stub.asInterface(service);
            try {
                downloadService.registerListener(downloadListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                Log.d("TestAidlActivity", "downloadService.getPid():" + downloadService.getPid());
                downloadService.getAidlBean("jacksen");
                downloadService.startDownload("http://www.baidu.com");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            downloadService = null;
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_DOWNLOAD_PROGRESS:
                    Log.d("TestAidlActivity", "progress: " + msg.obj);
                    break;
            }
        }
    };

    private IDownloadListener downloadListener = new IDownloadListener.Stub() {
        @Override
        public void onDownloadInterrupt(int progress) throws RemoteException {

        }

        @Override
        public void onDownloadProgress(int progress) throws RemoteException {
            mHandler.obtainMessage(MSG_DOWNLOAD_PROGRESS, progress).sendToTarget();
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (downloadService!=null && downloadService.asBinder().isBinderAlive()){
            try {
                downloadService.unregisterListener(downloadListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        unbindService(mConnection);
    }
}
